package org.ciallo.simplemusicplayer.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.android.material.imageview.ShapeableImageView;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.data.model.PlaylistInfo;
import timber.log.Timber;

import java.util.Locale;

/**
 * @author Jukomu
 * @Description: 用于 "添加到歌单" 对话框中显示歌单列表的适配器
 * @Package: org.ciallo.simplemusicplayer.adapter
 * @Project: SimpleMusicPlayer
 * @name: PlaylistSelectionAdapter
 * @Date: 2025/6/3-05:32
 * @Filename: PlaylistSelectionAdapter
 */
public class PlaylistSelectionAdapter extends ListAdapter<PlaylistInfo, PlaylistSelectionAdapter.PlaylistSelectionViewHolder> {

    private final OnPlaylistSelectedListener listener;

    public interface OnPlaylistSelectedListener {
        void onPlaylistSelected(PlaylistInfo playlistInfo);
    }

    public PlaylistSelectionAdapter(OnPlaylistSelectedListener listener) {
        super(DIFF_CALLBACK);
        this.listener = listener;
    }

    private static final DiffUtil.ItemCallback<PlaylistInfo> DIFF_CALLBACK = new DiffUtil.ItemCallback<PlaylistInfo>() {
        @Override
        public boolean areItemsTheSame(@NonNull PlaylistInfo oldItem, @NonNull PlaylistInfo newItem) {
            return oldItem.id == newItem.id;
        }

        @Override
        public boolean areContentsTheSame(@NonNull PlaylistInfo oldItem, @NonNull PlaylistInfo newItem) {
            return oldItem.equals(newItem);
        }
    };

    @NonNull
    @Override
    public PlaylistSelectionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_playlist_selection, parent, false);
        return new PlaylistSelectionViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PlaylistSelectionViewHolder holder, int position) {
        PlaylistInfo playlistInfo = getItem(position);
        if (playlistInfo != null) {
            holder.bind(playlistInfo, listener);
        }
    }

    static class PlaylistSelectionViewHolder extends RecyclerView.ViewHolder {
        ShapeableImageView ivCover;
        TextView tvName;
        TextView tvCount;

        PlaylistSelectionViewHolder(View itemView) {
            super(itemView);
            Timber.d("Looking for ID: imageView_playlist_selection_cover, Integer value: %d (Hex: %s)",
                    R.id.imageView_playlist_selection_cover,
                    Integer.toHexString(R.id.imageView_playlist_selection_cover));
            ivCover = itemView.findViewById(R.id.imageView_playlist_selection_cover);
            tvName = itemView.findViewById(R.id.textView_playlist_selection_name);
            tvCount = itemView.findViewById(R.id.textView_playlist_selection_count);

            // 添加一个检查，看 ivCover 是否为 null
            if (ivCover == null) {
                Timber.e("CRITICAL: PlaylistSelectionViewHolder - ivCover is NULL after findViewById! Check layout item_playlist_for_selection.xml for ID imageView_playlist_selection_cover.");
            }
        }

        void bind(final PlaylistInfo playlistInfo, final OnPlaylistSelectedListener listener) {
            ivCover = itemView.findViewById(R.id.imageView_playlist_selection_cover);
            tvName.setText(playlistInfo.name);
            tvCount.setText(String.format(Locale.getDefault(), "%d首", playlistInfo.songCount));

            Context context = itemView.getContext();
            Timber.d("Binding playlist: %s, Cover URI String: %s", playlistInfo.name, playlistInfo.displayCoverArtUri);
            Uri coverToLoad = null;
            if (playlistInfo.displayCoverArtUri != null && !playlistInfo.displayCoverArtUri.isEmpty()) {
                try {
                    coverToLoad = Uri.parse(playlistInfo.displayCoverArtUri);
                    Timber.d("Parsed Cover URI: %s", coverToLoad);
                } catch (Exception e) {
                    Timber.e(e, "Error parsing displayCoverArtUri for playlist selection: %s", playlistInfo.displayCoverArtUri);
                }
            } else {
                Timber.d("displayCoverArtUri is null or empty for playlist: %s", playlistInfo.name);
            }
            Timber.d("PlaylistSelectionViewHolder.bind: ivCover is null? %b", (ivCover == null));
            if (ivCover == null) {
                // 如果这里为true，那么问题就是 findViewById 没找到或者XML ID不对
                return; // 或者抛出更明确的异常
            }

            Glide.with(context)
                    .load(coverToLoad) // coverToLoad 是 Uri.parse(playlistInfo.displayCoverArtUri) 的结果
                    .placeholder(R.drawable.default_playlist_cover)
                    .error(R.drawable.default_playlist_cover)
                    .listener(new RequestListener<Drawable>() { // <--- 添加错误监听器
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            Timber.e(e, "Glide onLoadFailed for PlaylistSelectionAdapter. URI: %s", model);
                            // e 包含了具体的错误信息，例如权限问题、网络问题、解码错误等
                            return false; // 返回false让Glide继续处理error()占位符
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            Timber.d("Glide onResourceReady for PlaylistSelectionAdapter. URI: %s", model);
                            return false; // 返回false让Glide继续将resource设置到target
                        }
                    })
                    .into(ivCover);

            itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onPlaylistSelected(playlistInfo);
                }
            });
        }
    }
}
